package com.example.commonUpAndDownFileutil.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api/download")
public class DownloadController {
    // 与上传接口保持一致的文件存储路径
    private static final String UPLOAD_DIR = "uploads/";

    /**
     * 根据文件名下载文件
     * @param fileName 要下载的文件名（上传时返回的唯一文件名）
     * @return 响应实体包含文件流
     */
    @GetMapping("/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        try {
            // 构建文件路径
            File file = new File(UPLOAD_DIR + fileName);

            // 检查文件是否存在
            if (!file.exists() || !file.isFile()) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

            // 创建文件资源
            Resource resource = new FileSystemResource(file);

            // 构建响应头
            String contentType = "application/octet-stream";
            String headerValue = "attachment; filename=\"" +
                    URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()) + "\"";

            return ResponseEntity.ok()
                    .contentType(org.springframework.http.MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, headerValue)
                    .body(resource);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 带原始文件名的下载接口
     * @param fileName 存储的唯一文件名
     * @param originalName 原始文件名（用于下载时显示）
     * @return 响应实体包含文件流
     */
    @GetMapping
    public ResponseEntity<Resource> downloadFileWithOriginalName(
            @RequestParam String fileName,
            @RequestParam(required = false) String originalName) {
        try {
            File file = new File(UPLOAD_DIR + fileName);

            if (!file.exists() || !file.isFile()) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

            Resource resource = new FileSystemResource(file);
            String contentType = "application/octet-stream";

            // 如果提供了原始文件名，则使用原始文件名，否则使用存储的文件名
            String displayName = originalName != null && !originalName.isEmpty()
                    ? originalName
                    : fileName;

            // 编码文件名以支持中文
            String encodedFileName = URLEncoder.encode(displayName, StandardCharsets.UTF_8.name());
            String headerValue = "attachment; filename=\"" + encodedFileName + "\"";

            return ResponseEntity.ok()
                    .contentType(org.springframework.http.MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, headerValue)
                    .body(resource);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

